//
//  GroupInfoCtr.swift
//  eemall
//
//  Created by zhuxietong on 2018/12/27.
//  Copyright © 2018 tianrun. All rights reserved.
//

import UIKit
import AsyncDisplayKit
import soapp
import Eelay
// import mosdks

class GroupGoodsWebNode: WebCellNode {
 
    
    override func loadWeb(model: NSMutableDictionary) {
        webNode.eeWebView?.template = "商品图文1"
        if let url = URL(string: model["goods.contentdetail",""])
        {
            let req = URLRequest(url: url)
            webNode.eeWebView?.webView.load(req)
        }
    }
    
    
    override func replace(_ tag: String) -> String {
        if tag == "content"{
            return mo.model["goods.content",""]
        }
        return ""
    }
    

    
}

public enum GroupPurchaseStatus:String{
    case process = "1"
    case success = "2"
    case failed = "3"
    
    func numDesc(num:Int)->NSMutableAttributedString{
        switch self {
        case .success:
            let name = "共[XX]人参与".replaceVars(values: "\(num)")
            return name.ui.font12.color(color:._foreground).astring
//            return "共".ui.font12.cl_111.astring + "\(num)".ui.font13.color(hex: AppTheme.main_hex).astring + "人参与".ui.font12.cl_111.astring
        case .failed:
            let name = "缺少[XX]个名额".replaceVars(values: "\(num)")
            return name.ui.font12.color(color:._foreground).astring
//            return "缺".ui.font12.cl_111.astring + "\(num)".ui.font13.color(hex: AppTheme.main_hex).astring + "个名额".ui.font12.cl_111.astring
        case .process:
            let name = "剩余[XX]个名额".replaceVars(values: "\(num)")
            return name.ui.font12.color(color:._foreground).astring
//            return "剩余名额".loc.ui.font12.cl_111.astring + " \(num)".ui.font13.color(hex: AppTheme.main_hex).astring
        }
    }
    
}


public enum GroupDisplayType:String{
    case join = "join"
    case share = "share"
}

open class GroupInfoCtr: ASListController {
    
    public let detailWebView = EeWebView()
    
    public var dispaly:GroupDisplayType = .share

    public var bar = GroupGoodsDetailCtr.GroupBuyBar()

    open var sections:TP.section{
        get{
            
            let sec:TP.section = [
                [
                    ["cellID":"goods","__model":mo.detail],
                    ["cellID":"members","__model":mo.detail],
                    ["cellID":"share","__model":mo.detail,"display":dispaly.rawValue,"joined":"YES"],
                    ["cellID":"blank","height":"8"],
//                    ["cellID":"section","title":"商品信息"],
                ],
                [
                    ["cellID":"detail","__mdoel":mo.detail],
                ]
                //                SandBox.section(count: 5)
            ]
            return sec
        }
    }
    public var selector:TP.selector = [
        "cellID<members>":MembersCell.self,
        "cellID<goods>":GoodsCell.self,
        "cellID<share>":ShareCell.self,
        "cellID<detail>":GroupGoodsWebNode.self,
        "cellID<section>":SectionTitleNode.self,
        "cellID<blank>":BlankNode.self
    ]
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        title = "组团详情".loc
        tableNode.view.separatorStyle = .none
//        tableNode.load(sections: sections, selector: selector)
        weak var wself = self
        __notice.observer(Goods.Notice.groupOrderChange) { (noticeType, notify) in
            wself?.mo_request_send()
        }
        mo_request_send()
        
    }
    
  
    override open func layTable(tableView: UIView) {
        jo_contentView.eelay = [
            [tableView,[ee.T.L.R.B]],
//            [bar,[]],
        ]
        bar.controller = self
    }
    
    var invitationCode:String?{
        get{
            if mo.model["invitationCode",""].len > 0{
                return mo.model["invitationCode",""]
            }
            return nil
        }
    }
    
    
    var ID:String{
        get{
            return mo.model["teamid",""]
        }
    }
    
    var goods = NSMutableDictionary(){
        didSet{
            bar.mo.controller = self
            bar.mo.model = goods
        }
    }
    
    override open func mo_model_reload() {
        
        self.__link = "groups?teamid=\(ID)&orderid=\(mo.model["orderid",""])"
        //        self.__link = EeURLCreator(path: GroupLink.groupOrder.rawValue, params: ["teamid":teamid,"orderid":orderID]).rawUrl
        //        print("++++++PPP|\(self.__link)")
        
    }
    
    lazy var hud:HUD = {
        return HUD(at: self.view)
    }()
    open func getGoodsDetail(needHud:Bool,next:@escaping (NSMutableDictionary)->Void) {
        if needHud
        {
            
            hud.show().mode(.indeterminate)

        }
//        print("++++++++SSII")
        JoTask().get._surl(.团购商品详情).params(["id":goodsID]).json_handle {[weak self] (status, msg, obj, resp) in
            if needHud{
                self?.hud.hide(animated: true)
            }
            if status.isSuccess
            {
                if let dict = obj as? NSMutableDictionary
                {
                    self?.goods = dict
                    return
                }
            }
            if needHud{
                JoAlertView(info: "提示","获取组团信息失败","取消").append(title: "重试", style: .default, action: {
                    self?.getGoodsDetail(needHud: needHud, next: next)
                }).show(at: self)
            }
        }.run()
    }
    
    open override func mo_request_send() {
        loadingV.loading()
        JoTask().get._surl(.组团详情).params(["teamid":ID]).log.log_response().json_handle {[weak self] (status, msg, obj, resp) in
            if status.isSuccess
            {
                if let dict = obj as? NSMutableDictionary
                {
                    self?.mo.detail = dict
                    self?.loadingV.dismiss()
                    return
                }
            }
            self?.mo_request_alert(msg: msg)
            }.run()
    }
    
    override open func mo_detail_reload() {
        GMsgType.groups.msg.readOne(ID: ID)
        load(sections: sections, selector: selector)
        tableNode.reloadData()
        getGoodsDetail(needHud: false) { (obj) in}
    }
    
    public var goodsID:String{
        get{
            //            print("++++UUU--===|\(mo.model)")
            var id = mo.detail["goods.goodsid",""]
            if id.len < 1
            {
                id = mo.detail["goods.id",""]
            }
            return id
        }
    }
    
   
    
//    override open func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode {
//        let node = super.tableNode(tableNode, nodeForRowAt: indexPath)
//        if let webNode = node as? GroupGoodsWebNode{
//            if webNode.eeWebView == nil
//            {
//                webNode.eeWebView = self.detailWebView
//                webNode.load(model: mo.detail)
//            }
//        }
//        return node
//    }
    
    override open func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        switch actionID {
        case EeWebView.updateWebHeightKey:
            //                let row = model[int:"__row__",0]
            //                let section = model[int:"__section__",0]
            //                let indexP = IndexPath(row: row, section: section)
            //                tableNode.reloadRows(at: [indexP], with: .none)
            //                IndexSet(integer: 2)
            tableNode.reloadSections(IndexSet(integer: 1), with: .fade)
        case "join":
//            print("+++++++OOOOSS")
            var ladder_id:String? = nil
            let groupId = mo.detail["order.ladder_id","0"]
            if groupId == "0"{}else{ladder_id = groupId}
            GroupGoodsDetailCtr.preDealDetail(detail: goods, groupid: groupId)

            let price = goods[float:"__groupsprice",0]
            bar.joinGroup(groupID: ladder_id, teamID: mo.detail["order.teamid",""], price: price,invitationCode: mo.model["invitationCode",""])
        case "timeout":
            mo_request_send()
        default:
            break
        }
    }
    
    deinit {
        //        print("++++++finish GoodsDetailCtr")
    }
}

extension GroupInfoCtr{
    
    class SectionTitleNode: JoCellNode {
        let titleL = ASTextNode2()
        
        override func mo_model_reload() {
            titleL.attributedText = mo.model["title",""].ui.bfont12.cl_999.center.astring
            backgroundColor = UIColor.table_bg_color
        }
        
        override func specGetter() -> _Spec {
            let spec = _Spec.stack(["v",&-.center,[20,0,6,0]], childs: [
                titleL.Spec
                ])
            return spec
        }
    }
    
    class UserHeadNode: MoDisplayNode {
        let headV = JoImageNode()
        let tag = ASButtonNode()
        
        let noImg = ASImageNode()
        override func specGetter() -> _Spec {
            var head = _Spec.center([], xy: .xy, child: headV["38",38])
            head = _Spec.over([], over: _Spec.center([], xy: .xy, child: noImg[38,"38"]), back: head)
            
            head = _Spec.over([], over: _Spec.stack(["v",&-.center,_justfy(.flex_end)], childs: [tag.Spec]), back: head)
            
            return head


        }
        override func mo_model_reload() {
            headV.view.bsui.set(radius: 19, width: 1, color: UIColor(shex: "#ccc8"))
            noImg.view.bsui.set(radius: 19, width: nil, color: nil)

            let img = UIImage(named: "default_head") ?? UIImage.image(UIColor(shex: "#f6f6f6"))
            headV.ui.holder(type: .image(img))
            let head = mo.model["avatar",""]
            
            if head.len > 1
            {
                noImg.image = nil
            }
            else{
                noImg.image = UIImage(named: "head_waiting")
            }
            headV.img_url = head
            _ = tag.ui.font(size: 9).ntitle(title: "拼主".loc).ncolor(hex: "#fff").buttonColor(hex: AppTheme.main_hex).padding(insets: [1,3]).corner2
            
            if mo.model["__index__",""] == "0"{
                tag.alpha = 1
            }
            else{
                tag.alpha = 0
            }
        }
    }
    
    
    class GoodsCell: JoCellNode {
        let imgV = JoImageNode()
        let nameL = ASTextNode2()
        let optionL = ASTextNode2()
        let priceL = ASTextNode2()
        
        override func cellTouch() {
            
        }
        
        override func mo_model_reload() {
            
            let obj = DataNode.path(node: "__model.goods", mo.model, value: NSMutableDictionary())
            imgV.img_url = obj["thumb",""]
            backgroundColor = ._cellBackground
            nameL.attributedText = obj["title",""].ui.font14.color(color:._foreground).astring
            priceL.attributedText = "\("团购价".loc):".ui.font12.color(color:._foreground).astring + "¥ ".ui.font11.color(hex: "#5FB187").astring + _Tool.price1(obj["groupsprice",""])
            optionL.attributedText = obj["optiontitle",""].ui.font12.cl_888.astring
        }
        
        override func specGetter() -> _Spec {
            let spec = _Spec.stack(["h|10",&-.stretch,[20,AppTheme.edge,10,AppTheme.edge]], childs: [
                imgV[80,"80"],
                _Spec.stack(["v|8",_grow(1),_shrink(1)], childs: [
                    nameL.Spec,
//                    optionL.Spec,
                    priceL.Spec
                    ])
                ])
            return spec
         
        }
    }
    
    
    class ShareCell: JoCellNode {
        
        class StepBar: MoDisplayNode {
            let name1 = ASButtonNode()
            let tag1 = ASImageNode()
            let name2 = ASButtonNode()
            let tag2 = ASImageNode()            
            let name3 = ASButtonNode()

            override func mo_model_reload() {
                name1.ui.ntitle(title: "邀请好友参团".loc).ncolor(color:._foreground).font(size: 12)
                name2.ui.ntitle(title: "拼团成功发货".loc).ncolor(color:._foreground).font(size: 12)
                name3.ui.ntitle(title: "人数不足自动退款".loc).ncolor(color:._foreground).font(size: 12)
                tag1.image = UIImage(named: "f_more_indicator")
                tag2.image = UIImage(named: "f_more_indicator")
            }
            
            override func specGetter() -> _Spec {
                let spec = _Spec.stack(["h|4",_shrink(1),_justfy(.center),&-.center], childs: [
                    name1["20"],
                    tag1["16",16],
                    name2["20"],
                    tag2["16",16],
                    name3["20"],
                ])
                return spec
            }
            
        }
        
        
        let shareBt = ASButtonNode()
        let stepBar = StepBar()
        var groupStatus = GroupPurchaseStatus.failed
        override func specGetter() -> _Spec {
            let spec = _Spec.stack(["v|16",[26,0,26,0],&-.center], childs: [
                shareBt[(Swidth-2*AppTheme.edge)],
                stepBar.Spec
            ])
            
            return spec
        }
        
        override func addLayoutRules() {
            shareBt.addTarget(self, action: #selector(doAction), forControlEvents: .touchUpInside)
            view.backgroundColor = ._cellBackground
        }
        
        override func mo_model_reload() {
            stepBar.mo_model_reload()
            let obj = DataNode.path(node: "__model.order", mo.model, value: NSMutableDictionary())
            
            groupStatus = GroupPurchaseStatus(rawValue: mo.model["__model.order.status",""]) ?? .failed
            
            
            shareBt.bsui.set(radius: ThemeSet.buttonRadius, width: nil, color: nil)
            shareBt.setBackgroundImage(UIImage.gradient(colors: ThemeSet.Gradient.buy, size: [(Swidth - 50),44]), for: .normal)
            
            switch groupStatus {
            case .process:
                if obj["isjoin",false.tag] == true.tag
                {
                    _ = shareBt.ui.font(size: 13).ncolor(hex: "#fff").ntitle(title: "邀请组团".loc).padding(insets: [10,30])
                }
                else{
                    _ = shareBt.ui.font(size: 13).ncolor(hex: "#fff").ntitle(title: "加入组团".loc).padding(insets: [10,30])
                }
                
            case .success:
                _ = shareBt.ui.font(size: 13).ncolor(hex: "#fff").ntitle(title: "拼团成功".loc).padding(insets: [10,30])
                

            case .failed:
                shareBt.setBackgroundImage(UIImage.gradient(colors: ThemeSet.Gradient.disable, size: [(Swidth - 50),44]), for: .normal)

                _ = shareBt.ui.font(size: 13).ncolor(hex: "#fff").ntitle(title: "拼团结束".loc).padding(insets: [10,30])

            }
            
        }
        
        @objc func doAction(){
            let obj = DataNode.path(node: "__model.order", mo.model, value: NSMutableDictionary())
            
            switch groupStatus {
            case .process:
                if obj["isjoin",false.tag] == true.tag{
                    let obj = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
                    let title = obj["goods.title",""] + "团购中".loc
                    let content = obj.possible("title","desc", default: "")
                    let icon = obj["goods.thumb",""]
//                    let shareLink = "http://shopping.firstvar.com/group/detail/" + obj["order.teamid",""] + "?from=appShare"
                    
                    let shareLink = obj["order.shareurl",""] + "&from=appShare"
                    
                    if let teamId = (mo.controller as? GroupInfoCtr)?.ID{
//                        shareLink = "https://probuyerglobal.com/app/index.html#/mekit/shop/group-buy/group-buy-share?id=\(teamId)"
                         let qute:ShareQute = .init(
                            title: title,
                            icon:icon,
                            link: shareLink, image: nil, desc: content)

                         let share = MoShare().qute(qute).finish({ (success, msg, _, _) in
                             }).show()
                                             
                    }
                    
                    
                 
                }
                else{
                    active(ID: "join")
                }
            default:
                break
            }
            
            
            //                AskFriend.shareAticle(obj: mo.model)
        }
    }

    
    class MembersCell: JoCellNode {
        
        var groupStatus:GroupPurchaseStatus = .process
        var heads = [UserHeadNode]()
        let numL = ASTextNode2()
        let finishTagL = ASTextNode2()
        let timeNode = EndTimerNode()
        
        let line = ASDisplayNode()
        
        override func addLayoutRules() {
            weak var wself = self
            
            timeNode.endTimeNotice = {
                "拼团结束".loc.alert()
                wself?.active(ID: "timeout")
            }
            view.backgroundColor = ._cellBackground
        }
        override func mo_model_reload() {
            line.backgroundColor = ._separator
            let obj = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
            
            let members = NSMutableArray()
            let num = obj[int:"order.groupnum",1]
            for i in Range(uncheckedBounds: (0,num)) {
                let user = DataNode.path(node: "teams.\(i)", obj, value: NSMutableDictionary())
                user["__index__"] = i
                members.add(user)
            }
            
            
            heads.removeAll()
            weak var ws = self
            members.list { (obj:NSMutableDictionary, i) in
                let h = UserHeadNode()
                h.mo.model = obj
                ws?.heads.append(h)
            }
            let end = stampToTime(obj["order.endtime",""])
//            let end1 = timeStringToDate("2019-01-21 10:02:50.00")
            timeNode.endTime = end
            timeNode.mo.model = mo.model
            checkStatus(isTimeOut: timeNode.isTimeout)
        }
        
        
        
        func checkStatus(isTimeOut:Bool) {
            finishTagL.attributedText = "结束".loc.ui.font13.color(color: ._foreground).astring
            self.groupStatus = GroupPurchaseStatus(rawValue: mo.model["__model.order.status",""]) ?? .failed
            
            let nms = nums
            switch groupStatus {
            case .failed:
                numL.attributedText = "\("拼团失败".loc)  " .ui.bfont13.color(color: ._tint).astring + groupStatus.numDesc(num: nms.left)
            case .process:
                numL.attributedText = "\("拼团进行中".loc)  ".ui.bfont13.color(color: ._foreground).astring + groupStatus.numDesc(num: nms.left)
            case .success:
                numL.attributedText = "\("拼团成功".loc)  ".ui.bfont13.color(color: ._tint).astring + groupStatus.numDesc(num: nms.total)
                let time = stampToTime(mo.model["__model.order.successtime",""])["yyyy-MM-dd日 HH:mm"]
//                let time = timeNode.endTime["yyyy年MM月dd日 HH:mm"]
                let year = Date()["yyyy-"]
                let str = time.replacingOccurrences(of: year, with: "")
                finishTagL.attributedText = "\(str) \("结束".loc)".ui.font13.color(color: ._foreground).astring
            }           
        }
        
        var nums:(total:Int,left:Int){
            get{
                let total = mo.model[int:"__model.order.groupnum",0]
                let members = mo.model[int:"__model.order.needmembers",0]
                return (total,members)
            }
        }
        
        
        
        override func specGetter() -> _Spec {
            let hds = heads.map { (node) -> _Spec in
                return node["46",46]
            }
        
            let w = Swidth - 2.0*AppTheme.edge
            let spec = _Spec.stack(["h",_justfy(.center),_wrap,Int(w)], childs:hds)
            
            var infoSpecs = [_Spec]()
            switch groupStatus {
            case .success:
                infoSpecs = [
                    numL[[2,0,0,0]],
                    finishTagL[[3,0,0,0]]
                ]
            default:
                infoSpecs = [
                    numL[[2,0,0,0]],
                    timeNode.Spec,
                    finishTagL[[3,0,0,0]]
                ]
            }
            
            
            let root = _Spec.stack(["v|10",&-.center], childs: [
                .inset([], [10,16], child: line["\(TP.separatorHeight)"]),
                spec,
                _Spec.stack(["h|6",_justfy(.center),_grow(1),&-.center,"40",Swidth], childs: infoSpecs)
            ])
            return root
        }
    }
    
}

